
<template>

    <div>
        <el-breadcrumb separator="/" style="color: black;font-weight: 700">
            <el-breadcrumb-item >首页</el-breadcrumb-item>
            <el-breadcrumb-item>航班变更管理</el-breadcrumb-item>
            <el-breadcrumb-item>航班航线</el-breadcrumb-item>
        </el-breadcrumb>
        <h1>航班航线变更</h1>
        <!--      搜索表单-->
        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item>
                    <el-input placeholder="始发站" v-model="searchCriteria.APCD1" clearable style="display: none"/>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="航班号" >
                    <el-input placeholder="航班号" v-model="searchCriteria.META_ID" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                    <el-button type="primary" @click="searchOnSubmit">查询</el-button>
                    <el-button @click="searchOnReset">取消</el-button>
                </el-form-item>
            </el-col>
        </el-row>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column
                    :prop="item.prop"
                    :label="item.label"
                    v-for="(item, index) in tableHeader"
                    :key="item.prop"
            >
                <template #default="scope">
                    <div
                            v-show="item.editable || scope.row.editable"
                            class="editable-row"
                    >
                        <template v-if="item.type === 'input'">
                            <el-input
                                    v-bind="{ readonly: ['ID','META_ID'].includes(item.prop) && scope.row.editable }"
                                    size="small"
                                    v-model="scope.row[item.prop]"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>
                        <template v-if="item.type === 'date'">
                            <el-date-picker
                                    v-model="scope.row[item.prop]"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>
                    </div>
                    <div
                            v-show="!item.editable && !scope.row.editable"
                            class="editable-row"
                    >
                        <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" >
                <template #default="scope">
                    <el-button
                            v-if="showAuditButton"
                            v-show="!scope.row.editable"
                            size="small"
                            type="warning"
                            @click="scope.row.editable = true"
                    >变更</el-button
                    >
                    <!--                    审核-->
                    <el-button
                            v-else
                            v-show="!scope.row.editable"
                            size="small"
                            type="success"
                            @click="audit(scope.row)"
                    >审核</el-button
                    >
                    <el-button
                            v-show="scope.row.editable"
                            size="small"
                            type="success"
                            @click="saveEditedRow(scope.row)"
                    >确定</el-button
                    >
                    <el-button
                            v-show="scope.row.editable"
                            size="small"
                            type="info"
                            @click="cancelEdit(scope.row)"
                    >取消</el-button
                    >


                </template>
            </el-table-column>

        </el-table>
<!--        审核模态框-->
        <el-dialog v-model="dialogVisible" title="审核变更操作" width="50%" @close="resetAuditForm">
            <el-form ref="addFormRef" :model="newAudit" label-width="80px">
                <!-- 当前用户 -->
                <el-form-item label="当前用户" disabled>
                    <el-input v-model="newAudit.username" readonly></el-input>
                </el-form-item>
<!--                当前角色-->
                <el-form-item label="当前角色" disabled>
                    <el-input v-model="newAudit.role" readonly></el-input>
                </el-form-item>
                <el-form-item label="审核状态">
                    <el-radio-group v-model="newAudit.statu">
                        <el-radio :value="'待审核'" label="待审核"></el-radio>
                        <el-radio :value="'审核通过'" label="审核通过"></el-radio>
                        <el-radio :value="'审核拒绝'" label="审核拒绝"></el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onAddHandler">确定</el-button>
<!--        <el-button type="primary" @click="saveEditedRow">确定</el-button>-->
      </span>
            </template>
        </el-dialog>

        <!-- 分页组件示例 -->
        <el-pagination
                background
                layout="prev, pager, next"
                :total="totalElements"
                :current-page="currentPage"
                :page-size="pageSize"
                @current-change="handlePageChange"
                style="margin-top: 20px;"
                v-if="showPagination"
        />
 </div>
</template>

<script setup>
    import { ref, reactive, onMounted,onUpdated,computed,nextTick } from 'vue';
    import {ElMessage, ElMessageBox} from 'element-plus'
    import axios from 'axios'; // 确保已导入axios

    const item = reactive({
        META_ID: "",
        APAT: "",
        APNO1: "",
        APNO2: "",
        APNO3: "",
        APCD1: "",
        APCD2: "",
        APCD3: "",
        STATU: "",
    });

    const header = {
        prop: "key",
        label: "自定义",
        editable: false,
        type: "input",
    };
    //表头
    const tableHeader = ref([
        {
            prop: "META_ID",
            label: "航班号",
            editable: false,
            type: "input"
        },
        {
            prop: "APAT",
            label: "航班属性",
            editable: false,
            type: "input",
        },
        {
            prop: "APCD1",
            label: "始发站",
            editable: false,
            type: "input"
        },
        {
            prop: "APCD2",
            label: "目的地",
            editable: false,
            type: "input"
        },
        {
            prop: "APCD3",
            label: "经停站",
            editable: false,
            type: "input"
        },
        {
            prop: "STATU",
            label: "审核状态",
            editable: false,
            type: "input"
        },
    ]);
    //表单内数据，从数据库获取
    const tableData = ref([]);

    const showPagination = ref(true);
    // 分页相关状态
    const currentPage = ref(1); // 当前页码，默认为第一页
    const pageSize = ref(10); // 每页显示数量，默认为5条
    const totalElements = ref(0);
    // 分页查询所有
    async function fetchFlightData(current = currentPage.value, size = pageSize.value) {
        try {
            const response = await axios.get('/flightUpdate/all', {
                params: {
                    currentPage: current,
                    pageSize: size
                }
            });

            if (!response.data.errorCode || response.data.errorCode === "200") {
                // 更新tableData时，考虑分页数据结构
                tableData.value = response.data.data.map(flight => ({
                    META_ID: flight.metaid,
                    //如果APAT值是‘2403’就显示'2403[国内]'，如果是2401就显示'该值+[国际]'
                    APAT: flight.apat ,
                    APCD1: flight.apcd1,
                    //如果apcd3值是空，就展示‘空’，并且把apcd2赋值给3，把apcd3赋值给2；否则展示apcd3的值
                    APCD2: flight.apcd2,
                    APCD3: flight.apcd3 ? flight.apcd3 : '无',
                    STATU: flight.statu,
                    editable: false,
                }));
                totalElements.value = response.data.total;
            } else {
                ElMessage.error(response.data.msg || '获取数据失败');
                console.error('Failed to fetch data. ErrorCode:', response.data.errorCode, ', Message:', response.data.msg);
            }
        } catch (error) {
            ElMessage.error('获取数据过程中发生错误');
            console.error('Error fetching data:', error);
        }
    }
    // 初始化时加载第一页数据
    onMounted(() => {
        fetchFlightData();
        showPagination.value=true;
        const authority = sessionStorage.getItem('authority');
        // 根据authority的值决定显示哪个按钮
        showAuditButton.value = authority === 'ROLE_common';
    });
    onUpdated(() => {
    });
    // 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
    function handlePageChange(page) {
        currentPage.value = page;
        fetchFlightData(page);
    }
    function handleEdit(row) {
        row.editable = true;
    }



    //修改
    async function saveEditedRow(row) {
        try {
            const updatedBlls = {
                metaid: row.META_ID,
                apat: row.APAT,
                apcd1: row.APCD1,
                apcd2: row.APCD2,
                //判断一下，如果APCD3 = ‘无’，就设置APCD3为空
                apcd3: row.APCD3 === '无' ? '' : row.APCD3,
                apno1: 1,
                apno2: 2,
                apno3: 3,
            };
            //判断APCD1,APCD2不能为空
            if (row.APCD1 === '' || row.APCD1 === '无' || row.APCD1 === null) {
                ElMessage.error('始发站不能为空');
                return;
            }
            if (row.APCD2 === '' || row.APCD2 === '无' || row.APCD2 === null) {
                ElMessage.error('目的地不能为空');
                return;
            }
            //规定APCD1，APCD2，APCD3只能输入字母数字
            if (!/^[a-zA-Z0-9]+$/.test(row.APCD1) || !/^[a-zA-Z0-9]+$/.test(row.APCD2) ) {
                ElMessage.error('请注意！地点只能是字母或数字组合');
                return;
            }

            //APCD3要么是'无'，要么是字母数字组合
            if (row.APCD3 !== '无' && !/^[a-zA-Z0-9]+$/.test(row.APCD3) &&row.APCD3 !== ''){
                ElMessage.error('经停站只能是字母或数字组合');
                return;
            }
            const response = await axios.put(`/flightUpdate/update`, updatedBlls);

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('更新成功');
                row.editable = false;
                await fetchFlightData();
            } else {
                ElMessage.error(response.data.msg || '更新失败，请重试');
            }
        } catch (error) {
            console.error('Error updating data:', error);
            ElMessage.error('更新过程中发生错误');
        }
    }
    //取消修改按钮
    const cancelEdit = (row) => {
        row.editable = false;
        //    恢复原来数据
        Object.assign(row, {
            ID: row.ID,
            META_ID: row.META_ID,
            BTNO: row.BTNO,
            CODE: row.CODE,
            ESTR: row.ESTR,
            EEND: row.EEND,
        });
        ElMessage.warning('已取消修改');
        fetchGateData();
    };



    //查询表单
    const searchCriteria = reactive({
        META_ID: "",
    });
    async function searchOnSubmit() {
        try {
            // 确保META_ID非空
            if (!searchCriteria.META_ID ) {
                ElMessage.warning("航班号不能为空");
                return;
            }
            //输入的不是数字
            if (isNaN(searchCriteria.META_ID)) {
                ElMessage.warning("航班号必须为数字");
                return;
            }
            const response = await axios.get(`/flightUpdate/find/${searchCriteria.META_ID}`);
            // 根据后端实际返回结构处理数据
            if (response.data.errorCode === "200"){
                tableData.value = response.data.data.map(flight => ({
                    META_ID: flight.metaid,
                    //如果APAT值是‘2403’就显示'2403[国内]'，如果是2401就显示'该值+[国际]'
                    APAT: flight.apat === '2403' ? '2403[国内]' : flight.apat === '2401' ? flight.apat + '[国际]' : flight.apat,
                    APCD1: flight.apcd1,
                    //如果apcd3值是空，就展示‘空’，并且把apcd2赋值给3，把apcd3赋值给2；否则展示apcd3的值
                    APCD2: flight.apcd2,
                    APCD3: flight.apcd3 ? flight.apcd3 : '无',
                    editable: false,
                }));
            showPagination.value =false;
            }
        } catch (error) {
            ElMessage.error('查询失败，请检查网络或输入内容');
            console.error('查询错误:', error);
        }
    }
    //查询取消
    const searchOnReset =async () => {
        searchCriteria.META_ID = "";
        tableData.value = []; // 查询重置时清空表格数据
        showPagination.value = true;
        await fetchFlightData();
    };


//    审核
    //

    // 定义一个响应式变量来控制按钮的显示
    const showAuditButton = ref(false);
    const dialogVisible = ref(false);

    // 获取sessionStorage中的loginUser值
    const loginUserJSON = sessionStorage.getItem('loginUser');
    const loginUser = loginUserJSON ? JSON.parse(loginUserJSON) : {};

    //获取sessionStorage中的authority值
    const authority = sessionStorage.getItem('authority');

    //获取sessionStorage中的email值
    const email = sessionStorage.getItem('email');


    // 定义newAudit响应式对象
    const newAudit = reactive({
        username: loginUser.username || '', // 如果loginUser存在，则使用其username，否则为空字符串
        // role: authority || '',
        email: email || '',
        //如果authority是ROLE_vip，就设置role为管理员
        role: authority === 'ROLE_vip' ? '管理员' : '',
        statu: "待审核",
        metaid: "",
        apat: "",
        apcd1: "",
        apcd2: "",
        apcd3: "",
        apno1: 1,
        apno2: 2,
        apno3: 3,
    });

    // 添加表单的引用
    const addFormRef = ref(null);

    const audit = (row) => {
        dialogVisible.value = true;
        //    把row的数据给
        newAudit.metaid = row.META_ID;
        newAudit.apat = row.APAT;
        newAudit.apcd1 = row.APCD1;
        newAudit.apcd2 = row.APCD2;
        newAudit.apcd3 = row.APCD3;
        newAudit.apno1 = row.APNO1;
        newAudit.apno2 = row.APNO2;
        newAudit.apno3 = row.APNO3;
        newAudit.apno1 = 1;
        newAudit.apno2 = 2;
        newAudit.apno3 = 3;
        // Object.assign(row, {
        //     editable: true,
        // });
    };
    // 重置添加表单
    const resetAuditForm = () => {
        newAudit.statu = "待审核";
    };

    async function onAddHandler() {
        // 验证表单
        if (!addFormRef.value) return;

        // 发送添加请求到后端
        try {
            // const response = await axios.put(`/flightUpdate/update`, updatedBlls);
            const response = await axios.put(`/flightUpdate/update`,newAudit); // 替换为实际审核API URL

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('审核状态更新成功');
                dialogVisible.value = false;
                // 可能需要刷新相关数据
                await fetchFlightData();
            } else {
                ElMessage.error(response.data.msg || '更新审核状态失败，请重试');
            }
        } catch (error) {
            console.error('Error updating audit status:', error);
            ElMessage.error('更新审核状态过程中发生错误');
        }
    }
</script>

<style scoped>

</style>